package cn.qn.common.util;

import cn.qn.common.constants.AppConstants;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * Created by nishu on 2018/4/23.
 */
public class JwtUtil {


    /**
     * 根据用户token获取用户openId
     *
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        return Jwts.parser().setSigningKey(AppConstants.APP_KEY).parseClaimsJws(token).getBody().getSubject();
    }

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public static String generateAppToken(String userId) {
        long nowMillis = System.currentTimeMillis();
        Date issuedAt = new Date(nowMillis);
        Date expDate = new Date(nowMillis + AppConstants.TOKEN_EXPIRE_DAY * 24 * 60 * 60 * 1000);
        return Jwts.builder().setSubject(userId).setIssuedAt(issuedAt)
                .signWith(SignatureAlgorithm.HS256, AppConstants.APP_KEY).setExpiration(expDate).compact();
    }

}
